<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是shell——变量与替换相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV02-02-shell-02-变量与替换">
<meta property="og:url" content="https://sumumm.github.io/post/d8e0ae4.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是shell——变量与替换相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV02-%E7%BC%96%E8%AF%91%E5%9F%BA%E7%A1%80/LV02-02-shell-02-%E5%8F%98%E9%87%8F%E4%B8%8E%E6%9B%BF%E6%8D%A2/img/image-20220209090903335.png">
<meta property="article:published_time" content="2022-02-21T02:53:16.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:56.988Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV02-编译基础">
<meta property="article:tag" content="shell脚本">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV02-%E7%BC%96%E8%AF%91%E5%9F%BA%E7%A1%80/LV02-02-shell-02-%E5%8F%98%E9%87%8F%E4%B8%8E%E6%9B%BF%E6%8D%A2/img/image-20220209090903335.png">


<link rel="canonical" href="https://sumumm.github.io/post/d8e0ae4.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/d8e0ae4.html","path":"post/d8e0ae4.html","title":"LV02-02-shell-02-变量与替换"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV02-02-shell-02-变量与替换 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81-shell-%E5%8F%98%E9%87%8F"><span class="nav-text">一、 shell 变量</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%8F%98%E9%87%8F%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="nav-text">1.变量的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8F%98%E9%87%8F%E7%9A%84%E8%B5%8B%E5%80%BC"><span class="nav-text">2.变量的赋值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%8F%98%E9%87%8F%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-text">3.变量的使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E5%8F%98%E9%87%8F%E7%9A%84%E7%B1%BB%E5%9E%8B"><span class="nav-text">4.变量的类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-Bourne-Shell-%E4%B8%AD%E7%9A%84%E5%B8%B8%E7%94%A8%E7%9A%84%E5%9B%9B%E7%A7%8D%E5%8F%98%E9%87%8F"><span class="nav-text">5. Bourne Shell 中的常用的四种变量</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1%E7%94%A8%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F"><span class="nav-text">5.1用户自定义变量 </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2%E4%BD%8D%E7%BD%AE%E5%8F%98%E9%87%8F"><span class="nav-text">5.2位置变量 </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3%E9%A2%84%E5%AE%9A%E4%B9%89%E5%8F%98%E9%87%8F"><span class="nav-text">5.3预定义变量 </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F"><span class="nav-text">5.4环境变量</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-text">6.字符串 </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1-%E4%BD%BF%E7%94%A8%E6%A0%BC%E5%BC%8F"><span class="nav-text">6.1 使用格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2%E6%8B%BC%E6%8E%A5%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-text">6.2拼接字符串</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-2-1%E4%BD%BF%E7%94%A8%E5%8D%95%E5%BC%95%E5%8F%B7%E6%8B%BC%E6%8E%A5"><span class="nav-text">6.2.1使用单引号拼接</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-2-2%E4%BD%BF%E7%94%A8%E5%8F%8C%E5%BC%95%E5%8F%B7%E6%8B%BC%E6%8E%A5"><span class="nav-text">6.2.2使用双引号拼接</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-3%E8%8E%B7%E5%8F%96%E5%AD%97%E7%AC%A6%E4%B8%B2%E9%95%BF%E5%BA%A6"><span class="nav-text">6.3获取字符串长度</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-3-1%E4%BD%BF%E7%94%A8%E6%A0%BC%E5%BC%8F"><span class="nav-text">6.3.1使用格式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-3-2%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">6.3.2使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-4%E6%8F%90%E5%8F%96%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-text">6.4提取字符串</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-4-1%E6%88%AA%E5%8F%96%E6%96%B9%E5%BC%8F-1"><span class="nav-text">6.4.1截取方式 1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-4-2-%E6%88%AA%E5%8F%96%E6%96%B9%E5%BC%8F-2"><span class="nav-text">6.4.2 截取方式 2</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5%E6%9F%A5%E6%89%BE%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E5%AD%97%E7%AC%A6"><span class="nav-text">6.5查找字符串中字符</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#6-5-1%E4%BD%BF%E7%94%A8%E6%A0%BC%E5%BC%8F"><span class="nav-text">6.5.1使用格式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#6-5-2%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">6.5.2使用实例</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81-shell-%E6%95%B0%E7%BB%84"><span class="nav-text">二、 shell 数组 </span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%AE%9A%E4%B9%89%E4%B8%80%E4%B8%AA%E6%95%B0%E7%BB%84"><span class="nav-text">1.定义一个数组 </span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%BC%95%E7%94%A8%E6%95%B0%E7%BB%84%E5%85%83%E7%B4%A0"><span class="nav-text">2.引用数组元素 </span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E8%8E%B7%E5%8F%96%E6%95%B0%E7%BB%84%E9%95%BF%E5%BA%A6"><span class="nav-text">3.获取数组长度 </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1%E4%BD%BF%E7%94%A8%E6%A0%BC%E5%BC%8F"><span class="nav-text">3.1使用格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.2使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81-Shell-%E6%9B%BF%E6%8D%A2"><span class="nav-text">三、 Shell 替换 </span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%8F%98%E9%87%8F%E6%9B%BF%E6%8D%A2"><span class="nav-text">1.变量替换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%91%BD%E4%BB%A4%E6%9B%BF%E6%8D%A2"><span class="nav-text">2.命令替换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1%E4%BD%BF%E7%94%A8%E6%A0%BC%E5%BC%8F"><span class="nav-text">2.1使用格式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">2.2使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81%E5%AD%97%E5%85%B8"><span class="nav-text">四、字典</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%AD%97%E5%85%B8%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="nav-text">1.字典的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%AD%97%E5%85%B8%E8%B5%8B%E5%80%BC"><span class="nav-text">2. 字典赋值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%AD%97%E5%85%B8%E7%9B%B8%E5%85%B3%E6%93%8D%E4%BD%9C"><span class="nav-text">3. 字典相关操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-%E6%89%93%E5%8D%B0%E6%8C%87%E5%AE%9Akey%E7%9A%84value"><span class="nav-text">3.1 打印指定key的value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-%E6%89%93%E5%8D%B0%E6%89%80%E6%9C%89key"><span class="nav-text">3.2 打印所有key</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-%E6%89%93%E5%8D%B0%E6%89%80%E6%9C%89value"><span class="nav-text">3.3 打印所有value</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-%E9%81%8D%E5%8E%86"><span class="nav-text">3.4 遍历</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5-%E4%B8%8D%E5%A3%B0%E6%98%8E%EF%BC%9F"><span class="nav-text">3.5 不声明？</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/d8e0ae4.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV02-02-shell-02-变量与替换 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV02-02-shell-02-变量与替换
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-02-21 10:53:16" itemprop="dateCreated datePublished" datetime="2022-02-21T10:53:16+08:00">2022-02-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV02-%E7%BC%96%E8%AF%91%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">LV02-编译基础</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.9k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>18 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是shell——变量与替换相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV02-%E7%BC%96%E8%AF%91%E5%9F%BA%E7%A1%80/LV02-02-shell-02-%E5%8F%98%E9%87%8F%E4%B8%8E%E6%9B%BF%E6%8D%A2/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center">---</td>        <td align="left">--- <a href="" target="_blank">  <i class="fa fa-external-link-alt"></i></a></td>      </tr></table>
              </div>
            </details>


<h1 id="一、-shell-变量"><a href="#一、-shell-变量" class="headerlink" title="一、 shell 变量"></a><font size=3>一、 shell 变量</font></h1><h2 id="1-变量的定义"><a href="#1-变量的定义" class="headerlink" title="1.变量的定义"></a><font size=3>1.变量的定义</font></h2><p>shell 允许用户建立变量存储数据，但<strong>不支持数据类型（整型、字符、浮点型）</strong>，将<strong>任何赋给变量的值都解释为一串字符</strong>。变量定义格式如下（支持三种形式）：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Variable=value   # 第一种</span><br><span class="line">Variable=&#x27;value&#x27; # 第二种</span><br><span class="line">Variable=&quot;value&quot; # 第三种</span><br></pre></td></tr></table></figure>

<p><strong>【注意】</strong></p>
<p>（1）<strong>等号两边不允许有空格</strong>。</p>
<p>（2）命名只能使用<strong>英文字母</strong>，<strong>数字</strong>和<strong>下划线</strong>，<strong>首个字符不能以数字开头</strong>，且中间不能有空格。</p>
<p>（3）不能使用标点符号，而且不能使用 bash 里的关键字（可用help命令查看保留关键字）。</p>
<p>（4）第二种与第三种的区别：</p>
<p>以单引号 ‘ ‘ 包围变量的值时，单引号里面是什么就输出什么，即使内容中有变量和命令（命令需要反引起来）也会把它们<strong>原样输出</strong>。这种方式比较适合定义显示纯字符串的情况，即不希望解析变量、命令等的情况。</p>
<p>以双引号 “ “ 包围变量的值时，输出时会先<strong>解析里面的变量和命令</strong>，而不是把双引号中的变量名和命令原样输出。这种方式比较适合字符串中附带有变量和命令并且想将其解析后再输出的变量定义。</p>
<h2 id="2-变量的赋值"><a href="#2-变量的赋值" class="headerlink" title="2.变量的赋值"></a><font size=3>2.变量的赋值</font></h2><p>在  Bash shell  中，每一个变量的值都是字符串，<strong>无论给变量赋值时有没有使用引号，值都会以字符串的形式存储</strong>。这就意味着， Bash shell  在默认情况下不会区分变量类型，即使将整数和小数赋值给变量，它们也会被视为字符串。</p>
<ul>
<li>直接赋值</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Variable=value</span><br></pre></td></tr></table></figure>

<ul>
<li>用语句赋值</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">赋值方式1</span></span><br><span class="line">Variable= command </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">赋值方式2</span></span><br><span class="line">Variable=$(command)</span><br></pre></td></tr></table></figure>

<p>【注意】</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">用语句进行赋值时，语句一定要写在     符号里边，该符号为英文状态下 Esc 按键下边的哪个按键。或者也可以用 $() 的方式，这种方式看起来要更直观一些。</span><br></pre></td></tr></table></figure>




<h2 id="3-变量的使用"><a href="#3-变量的使用" class="headerlink" title="3.变量的使用"></a><font size=3>3.变量的使用</font></h2><p>使用一个定义过的变量，只要在变量名前面加美元符号（ $ ）即可。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;Variable&#125;</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">Variable</span></span><br></pre></td></tr></table></figure>

<p>【注意】</p>
<p>（1）变量名外面的<strong>花括号是可选的</strong>，加不加都行，加花括号是为了帮助解释器识别变量的边界。推荐给所有变量加上花括号。</p>
<p>（2）定义变量和给变量赋值的时候都不需要加 $ ，使用的时候才需要加上。</p>
<h2 id="4-变量的类型"><a href="#4-变量的类型" class="headerlink" title="4.变量的类型"></a><font size=3>4.变量的类型</font></h2><ul>
<li><p>局部变量：在脚本或命令中定义，仅在当前 shell 实例中有效，其他 shell 启动的程序不能访问局部变量。</p>
</li>
<li><p>环境变量：所有的程序，包括 shell 启动的程序，都能访问环境变量，有些程序需要环境变量来保证其正常运行。必要的时候 shell 脚本也可以定义环境变量。</p>
</li>
<li><p>shell 变量：shell 变量是由 shell 程序设置的特殊变量。 shell 变量中有一部分是环境变量，有一部分是局部变量，这些变量保证了 shell 的正常运行。</p>
</li>
</ul>
<h2 id="5-Bourne-Shell-中的常用的四种变量"><a href="#5-Bourne-Shell-中的常用的四种变量" class="headerlink" title="5. Bourne Shell 中的常用的四种变量"></a><font size=3>5. Bourne Shell 中的常用的四种变量</font></h2><h3 id="5-1用户自定义变量"><a href="#5-1用户自定义变量" class="headerlink" title="5.1用户自定义变量 "></a><font size=3>5.1用户自定义变量 </font></h3><p>就是用户自己定义的变量，在 shell 编程中，通常使用全大写，例如</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">COUNT=1</span><br></pre></td></tr></table></figure>

<h3 id="5-2位置变量"><a href="#5-2位置变量" class="headerlink" title="5.2位置变量 "></a><font size=3>5.2位置变量 </font></h3><p>在  Linux  的命令行中，当一条命令或脚本执行时，后面可以跟多个参数，可以使用位置参数变量来表示这些参数。</p>
<table>
    <tr>
        <td align="center" width=100px>$n</td>
        <td align="left">n 为数字，$0 代表命令本身，$1-$9 代表第 1-9 个参数，10 以上的参数需要用大括号{}包含， 例如${10}，${15}</td>
    </tr>
    <tr>
        <td align="center" width=100px>$*</td>
        <td align="left">代表命令行中所有的参数，把所有的参数看成一个整体</td>
    </tr>
    <tr>
        <td align="center" width=100px>$@</td>
        <td align="left">代表命令行中所有的参数，不过 $@ 把每个参数区别对待</td>
    </tr>
    <tr>
        <td align="center" width=100px>$#</td>
        <td align="left">代表命令行中所有参数的个数</td>
    </tr>
</table>

<p><strong>【使用实例】</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">hk@ubuntu-22-04:~/1sharedfiles/6temp/myubuntu$ ./1.sh 1 2 3</span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">*=1 2 3</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash"><span class="comment">#=3</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">@=1 2 3</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">0=./1.sh</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">1=1</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">2=2</span></span><br></pre></td></tr></table></figure>

<p><strong>【注意】</strong></p>
<p>（1） $n 中， n 大于等于 10 时，一定要加上 {} 。</p>
<p>（2） $* 与 $@ ：</p>
<p>当  $* 和  $@  不被双引号 “ “ 包含时，它们之间<strong>没有任何区别</strong>，都是将接收到的每个参数看做一份数据，彼此之间<strong>以空格来分隔</strong>，两者都以 “$1” “$2” … “\$n”  的形式输出所有参数。</p>
<p>当  $* 和  $@  被双引号 “ “ 包含时， “$*“ 会将<strong>所有的参数从整体上看做一份数据</strong>，而不是把每个参数都看做一份数据，以 “$1 $2 … $n” 的形式输出所有参数； “$@” 仍然将<strong>每个参数都看作一份数据</strong>，彼此之间是独立的，以 “$1” “$2” … “$n”  的形式输出所有参数。</p>
<table>
    <tr>
        <td align="center" rowspan="2">变量</td>
        <td align="center" colspan="2">输出形式</td>
    </tr>
    <tr>
        <td align="center">被 " " 包含</td>
        <td align="center">不被 " " 包含</td>
    </tr>
    <tr>
        <td align="center">$*</td>
        <td align="center">"$1 $2 … $n"</td>
        <td align="center">"$1" "$2" … "$n"</td>
    </tr>
    <tr>
        <td align="center">$@</td>
        <td align="center">"$1" "$2" … "$n"</td>
        <td align="center">"$1" "$2" … "$n"</td>
    </tr>
</table>

<p>例如：某命令传递了  5  个参数，那么对于 “$*” 来说，这  5  个参数会合并到一起形成 1 个数据，这一个数据包含了 5 个参数，它们之间是<strong>无法分割</strong>的；而对于 “$@” 来说，这  5  个参数是<strong>相互独立</strong>的，它们是  5  个数据。</p>
<h3 id="5-3预定义变量"><a href="#5-3预定义变量" class="headerlink" title="5.3预定义变量 "></a><font size=3>5.3预定义变量 </font></h3><p>预定义变量是在  Shell  一开始时就定义的变量，这一点和默认环境变量有些类似。不同的是，<strong>预定义变量不能重新定义</strong>，用户只能根据  Shell  的定义来使用这些变量。严格来说，位置参数变量也是预定义变量的一种，只是位置参数变量的作用比较统一，所以一般把位置参数变量单独划分为一类变量。</p>
<table>
    <tr>
        <td align="center" width=100px>$?</td>
        <td align="left">最后一次执行的命令的返回状态。如果这个变量的值为 0，则证明上一条命令正确执行；如果这个变量的值为非0 (具体是哪个数由命令自己来决定)，则证明上一条命令执行错误。</td>
    </tr>
    <tr>
        <td align="center" width=100px>$$</td>
        <td align="left">代表当前进程的进程号(PID)。</td>
    </tr>
    <tr>
        <td align="center" width=100px>$!</td>
        <td align="left">代表后台运行的最后一个进程的进程号(PID)。</td>
    </tr>
</table>




<h3 id="5-4环境变量"><a href="#5-4环境变量" class="headerlink" title="5.4环境变量"></a><font size=3>5.4环境变量</font></h3><p>环境变量也称为全局变量，可以在创建它们的 Shell 及其派生出来的任意子进程 Shell 中使用，环境变量又可以分为自定义环境变量和 bash 内置的环境变量。</p>
<p>环境变量可以在命令行中设置和创建，用户退出命令行时这些变量值就会丢失，那如何永久保存环境变量呢？可以在用户家目录下的 .bash_profile(或者是.profile) 或 .bashrc(非用户登录模式特有，如：SSH) 文件中，这两个文件设置后是针对特定用户的，也可以在 &#x2F;etc&#x2F;profile 文件中定义环境变量，该文件设置后将会影响所有的用户，就是说在这三个文件中进行定义的环境变量在用户登录后就会进行初始化。</p>
<p>例如：下图为 ~&#x2F;.profile 文件内容。</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV02-%E7%BC%96%E8%AF%91%E5%9F%BA%E7%A1%80/LV02-02-shell-02-%E5%8F%98%E9%87%8F%E4%B8%8E%E6%9B%BF%E6%8D%A2/img/image-20220209090903335.png" style="zoom:50%;" />

<ul>
<li>常用环境变量</li>
</ul>
<table>
    <tr>
        <td align="center">HOME</td>
        <td align="left">/etc/passwd文件中列出的用户主目录 </td>
    </tr>
    <tr>
        <td align="center">PATH</td>
        <td align="left">系统默认的可执行文件搜索路径</td>
    </tr>
    <tr>
        <td align="center">HISTSIZE</td>
        <td align="left">保留历史命令的数目上限</td>
    </tr>
    <tr>
        <td align="center">OSTYPE</td>
        <td align="left">系统类型</td>
    </tr>
    <tr>
        <td align="center">PWD</td>
        <td align="left">当前工作目录</td>
    </tr>
    <tr>
        <td align="center">TERM</td>
        <td align="left">终端类型，常用的有vt100,ansi,vt200,xterm等 </td>
    </tr>
    <tr>
        <td align="center">PS1, PS2</td>
        <td align="left">默认提示符($)及换行提示符(>)  </td>
    </tr>
    <tr>
        <td align="center">IFS</td>
        <td align="left">Internal Field Separator, 默认为空格，tab及换行符</td>
    </tr>
</table>



<h2 id="6-字符串"><a href="#6-字符串" class="headerlink" title="6.字符串 "></a><font size=3>6.字符串 </font></h2><h3 id="6-1-使用格式"><a href="#6-1-使用格式" class="headerlink" title="6.1 使用格式"></a><font size=3>6.1 使用格式</font></h3><p>在 shell 中，字符串可以用单引号，也可以用双引号，也可以不用引号。</p>
<ul>
<li>单引号</li>
</ul>
<p>单引号里的任何字符都会原样输出，单<strong>引号字符串中的变量是无效的</strong>。单引号字串中不能出现单独一个的单引号（对单引号使用转义符后也不行），但可成对出现，作为字符串拼接使用。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">str=&#x27;string&#x27;</span><br></pre></td></tr></table></figure>

<ul>
<li>双引号</li>
</ul>
<p>双引号里可以有变量，也可以出现转义字符。</p>
<h3 id="6-2拼接字符串"><a href="#6-2拼接字符串" class="headerlink" title="6.2拼接字符串"></a><font size=3>6.2拼接字符串</font></h3><h4 id="6-2-1使用单引号拼接"><a href="#6-2-1使用单引号拼接" class="headerlink" title="6.2.1使用单引号拼接"></a><font size=3>6.2.1使用单引号拼接</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span> </span><br><span class="line">str1=&#x27;World&#x27;</span><br><span class="line"></span><br><span class="line">str2=&#x27;Hello,&#x27;$str1&#x27; !&#x27;</span><br><span class="line">str3=&#x27;Hello, $str1 !&#x27;</span><br><span class="line">echo $str2</span><br><span class="line">echo $str3</span><br></pre></td></tr></table></figure>

<p>输出结果为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Hello,World !</span><br><span class="line">Hello, $str1 !</span><br></pre></td></tr></table></figure>

<h4 id="6-2-2使用双引号拼接"><a href="#6-2-2使用双引号拼接" class="headerlink" title="6.2.2使用双引号拼接"></a><font size=3>6.2.2使用双引号拼接</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span> </span><br><span class="line">str1=&quot;World&quot;</span><br><span class="line"></span><br><span class="line">str2=&quot;Hello, &quot;$str1&quot; !&quot;</span><br><span class="line">str3=&quot;Hello, $str1 !&quot;</span><br><span class="line">echo $str2</span><br><span class="line">echo $str3</span><br></pre></td></tr></table></figure>

<p>输出结果为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Hello, World !</span><br><span class="line">Hello, World !</span><br></pre></td></tr></table></figure>

<h3 id="6-3获取字符串长度"><a href="#6-3获取字符串长度" class="headerlink" title="6.3获取字符串长度"></a><font size=3>6.3获取字符串长度</font></h3><h4 id="6-3-1使用格式"><a href="#6-3-1使用格式" class="headerlink" title="6.3.1使用格式"></a><font size=3>6.3.1使用格式</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;<span class="comment">#&lt;string&gt;&#125;</span></span></span><br></pre></td></tr></table></figure>

<ul>
<li>string ：为要获取长度的目标字符串变量。</li>
</ul>
<h4 id="6-3-2使用实例"><a href="#6-3-2使用实例" class="headerlink" title="6.3.2使用实例"></a><font size=3>6.3.2使用实例</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span> </span><br><span class="line">str1=&#x27;World&#x27;</span><br><span class="line">str2=&quot;World&quot;</span><br><span class="line"></span><br><span class="line">echo &quot;str1&#x27;s length=$&#123;#str1&#125;&quot;</span><br><span class="line">echo &quot;str1&#x27;s length=$&#123;#str2&#125;&quot;</span><br></pre></td></tr></table></figure>

<p>输出结果为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">str1&#x27;s length=5</span><br><span class="line">str1&#x27;s length=5</span><br></pre></td></tr></table></figure>

<h3 id="6-4提取字符串"><a href="#6-4提取字符串" class="headerlink" title="6.4提取字符串"></a><font size=3>6.4提取字符串</font></h3><h4 id="6-4-1截取方式-1"><a href="#6-4-1截取方式-1" class="headerlink" title="6.4.1截取方式 1"></a><font size=3>6.4.1截取方式 1</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;&lt;string&gt;:n:len&#125;</span></span><br></pre></td></tr></table></figure>

<p>提取出的字符串为 n 位置处字符极其之后的 len-1 个字符。</p>
<ul>
<li>string ：为要获取长度的目标字符串变量。</li>
<li>n ：为起始字符位置；</li>
<li>len ：为截取字符串的长度。</li>
</ul>
<p><strong>【注意】</strong>字符串中首个字符的索引为 0 。</p>
<p><strong>【使用实例】</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span> </span><br><span class="line">str1=&#x27;Hello, World&#x27;</span><br><span class="line">str2=&quot;Hello, World&quot;</span><br><span class="line"></span><br><span class="line">echo &quot;$&#123;str1:2:3&#125;&quot;</span><br><span class="line">echo &quot;$&#123;str2:2:7&#125;&quot;</span><br></pre></td></tr></table></figure>

<p>输出结果为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">llo</span><br><span class="line">llo, Wo</span><br></pre></td></tr></table></figure>

<h4 id="6-4-2-截取方式-2"><a href="#6-4-2-截取方式-2" class="headerlink" title="6.4.2 截取方式 2"></a><font size=3>6.4.2 截取方式 2</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;parameter<span class="comment">#*word&#125;  # 即从左向右截取第一个word后的字符串</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;parameter<span class="comment">##*word&#125; # 即从左向右截取最后一个word后的字符串</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;parameter%word*&#125;  <span class="comment"># 即从右向左截取第一个word前的字符串</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;parameter%%word*&#125; <span class="comment"># 即从右向左截取最后一个word前的字符串</span></span></span><br></pre></td></tr></table></figure>

<p><strong>【注意】</strong>上边的这些命令截取之后，都是不包含 word 的，所以如果开头或者结尾含有 word 的时候，可能会截取出来一个空的字符串。</p>
<p><strong>【使用实例】</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line">FILE_PATH=a/b/c/d/file.tar.gz</span><br><span class="line">echo &quot;\$&#123;FILE_PATH&#125;      = $&#123;FILE_PATH&#125;&quot;</span><br><span class="line">echo &quot;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH#*/&#125;   = $&#123;FILE_PATH#*/&#125;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH##*/&#125;  = $&#123;FILE_PATH##*/&#125;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH%/*&#125;   = $&#123;FILE_PATH%/*&#125;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH%%/*&#125;  = $&#123;FILE_PATH%%/*&#125;&quot;</span><br><span class="line">echo &quot;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH#*.&#125;   = $&#123;FILE_PATH#*.&#125;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH##*.&#125;  = $&#123;FILE_PATH##*.&#125;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH%.*&#125;   = $&#123;FILE_PATH%.*&#125;&quot;</span><br><span class="line">echo &quot;\$&#123;FILE_PATH%%.*&#125;  = $&#123;FILE_PATH%%.*&#125;&quot;</span><br></pre></td></tr></table></figure>

<p>输出的结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp$ ./1.sh </span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH&#125;      = a/b/c/d/file.tar.gz</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH<span class="comment">#*/&#125;   = b/c/d/file.tar.gz</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH<span class="comment">##*/&#125;  = file.tar.gz</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH%/*&#125;   = a/b/c/d</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH%%/*&#125;  = a</span></span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH<span class="comment">#*.&#125;   = tar.gz</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH<span class="comment">##*.&#125;  = gz</span></span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH%.*&#125;   = a/b/c/d/file.tar</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;FILE_PATH%%.*&#125;  = a/b/c/d/file</span></span><br></pre></td></tr></table></figure>



<h3 id="6-5查找字符串中字符"><a href="#6-5查找字符串中字符" class="headerlink" title="6.5查找字符串中字符"></a><font size=3>6.5查找字符串中字符</font></h3><h4 id="6-5-1使用格式"><a href="#6-5-1使用格式" class="headerlink" title="6.5.1使用格式"></a><font size=3>6.5.1使用格式</font></h4><p>可以通过 expr 实现字符串中特定字符的查找，这种查找方式会查找字符串中首次出现该字符的位置。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Variable= `expr index &quot;$&#123;&lt;string&gt;&#125;&quot; &lt;char&gt; `</span><br></pre></td></tr></table></figure>

<ul>
<li>string ：为要查找的目标字符串变量。</li>
<li>char ：为要查找的字符。</li>
</ul>
<p><strong>【使用实例】</strong></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">string=&quot;runoob is a great site&quot;</span><br><span class="line">echo `expr index &quot;$string&quot; o`  # 输出 4</span><br></pre></td></tr></table></figure>



<p><strong>【注意】</strong></p>
<p>（1）在查找过程中，字符串中首个字符的索引为 1 。</p>
<p>（2）以上脚本中 &#96; 是反引号，而不是单引号 **’**。</p>
<p>（3） char 可以是多个字符，例如对于 ac ， a ， c 两个字符哪个先出现，就会停止查找，返回首先出现的字符在目标字符串中的首次出现的位置。</p>
<h4 id="6-5-2使用实例"><a href="#6-5-2使用实例" class="headerlink" title="6.5.2使用实例"></a><font size=3>6.5.2使用实例</font></h4><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span> </span><br><span class="line">str1=&#x27;Hello, World&#x27;</span><br><span class="line">str2=&quot;Hello, World&quot;</span><br><span class="line"></span><br><span class="line">echo  expr index &quot;$str1&quot; &#x27; &#x27; </span><br><span class="line">echo  expr index &quot;$str2&quot; l </span><br></pre></td></tr></table></figure>

<p>输出结果为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">7</span><br><span class="line">3</span><br></pre></td></tr></table></figure>



<h1 id="二、-shell-数组"><a href="#二、-shell-数组" class="headerlink" title="二、 shell 数组 "></a><font size=3>二、 shell 数组 </font></h1><p> bash 支持一维数组（不支持多维数组），并且没有限定数组的大小。数组元素的下标由 0 开始。获取数组中的元素要用下标，下标可以是整数或算术表达式，其值应大于或等于0。</p>
<h2 id="1-定义一个数组"><a href="#1-定义一个数组" class="headerlink" title="1.定义一个数组 "></a><font size=3>1.定义一个数组 </font></h2><p>在  Shell  中，用<strong>括号</strong>来表示数组，数组元素用 &lt;space&gt; 符号分割开。</p>
<ul>
<li>直接定义</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">数组名=(值1 值2 ... 值n)</span><br></pre></td></tr></table></figure>

<p>例如：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">version=(v1 v2 v3)</span><br></pre></td></tr></table></figure>

<p>或者</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">version=(v1 </span><br><span class="line">         v2 </span><br><span class="line">         v3)</span><br></pre></td></tr></table></figure>

<ul>
<li>单独定义各个分量</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">数组名[0]=值0</span><br><span class="line">数组名[1]=值1</span><br><span class="line">数组名[n]=值n</span><br></pre></td></tr></table></figure>

<p><strong>【注意】</strong>可以不使用连续的下标，而且下标的范围没有限制。</p>
<h2 id="2-引用数组元素"><a href="#2-引用数组元素" class="headerlink" title="2.引用数组元素 "></a><font size=3>2.引用数组元素 </font></h2><ul>
<li>获取数组中某个元素</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;arrayName[index]&#125;</span></span><br></pre></td></tr></table></figure>

<p><strong>【注意】</strong> index 从 0 开始</p>
<ul>
<li>获取数组中所有元素</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;arrayName[@]&#125;</span></span><br><span class="line"><span class="meta prompt_">$</span><span class="language-bash">&#123;arrayName[*]&#125;</span></span><br></pre></td></tr></table></figure>

<h2 id="3-获取数组长度"><a href="#3-获取数组长度" class="headerlink" title="3.获取数组长度 "></a><font size=3>3.获取数组长度 </font></h2><h3 id="3-1使用格式"><a href="#3-1使用格式" class="headerlink" title="3.1使用格式"></a><font size=3>3.1使用格式</font></h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">length=$&#123;#arrayName[@]&#125;  # 取得数组元素的个数</span><br><span class="line">length=$&#123;#arrayName[*]&#125;  # 取得数组元素的个数</span><br><span class="line">lengthn=$&#123;#arrayName[n]&#125; # 取得数组单个元素的长度</span><br></pre></td></tr></table></figure>

<h3 id="3-2使用实例"><a href="#3-2使用实例" class="headerlink" title="3.2使用实例"></a><font size=3>3.2使用实例</font></h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span> </span><br><span class="line">a=(v1.1 v2 v3.3 )</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">取得数组元素的个数</span></span><br><span class="line">length=$&#123;#a[@]&#125;</span><br><span class="line">echo &quot;a&#x27;s length=$&#123;length&#125;&quot;</span><br><span class="line">length=$&#123;#a[*]&#125;</span><br><span class="line">echo &quot;a&#x27;s length=$&#123;length&#125;&quot;</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">取得数组单个元素的长度</span></span><br><span class="line">lengthn=$&#123;#a[0]&#125;</span><br><span class="line">echo &quot;a[0]&#x27;s length=$&#123;lengthn&#125;&quot;</span><br><span class="line">lengthn=$&#123;#a[1]&#125;</span><br><span class="line">echo &quot;a[1]&#x27;s length=$&#123;lengthn&#125;&quot;</span><br><span class="line">lengthn=$&#123;#a[n]&#125;</span><br><span class="line">echo &quot;a[n]&#x27;s length=$&#123;lengthn&#125;&quot;</span><br></pre></td></tr></table></figure>

<p>运行结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">a&#x27;s length=3</span><br><span class="line">a&#x27;s length=3</span><br><span class="line">a[0]&#x27;s length=4</span><br><span class="line">a[1]&#x27;s length=2</span><br><span class="line">a[n]&#x27;s length=4</span><br></pre></td></tr></table></figure>

<h1 id="三、-Shell-替换"><a href="#三、-Shell-替换" class="headerlink" title="三、 Shell 替换 "></a><font size=3>三、 Shell 替换 </font></h1><p>如果表达式中包含特殊字符， Shell  将会进行替换。</p>
<h2 id="1-变量替换"><a href="#1-变量替换" class="headerlink" title="1.变量替换"></a><font size=3>1.变量替换</font></h2><p>变量替换可以根据变量的状态（是否为空、是否定义等）来改变它的值。</p>
<table>
    <tr>
        <td align="left">${Variable}</td>
        <td align="left">变量本来的值</td>
    </tr>
    <tr>
        <td align="left">${Variable:-word}</td>
        <td align="left">如果变量 Variable 为空或已被删除(unset)，那么返回 word，但不改变 Variable 的值。</td>
    </tr>
    <tr>
        <td align="left">${Variable:=word}</td>
        <td align="left">如果变量 Variable 为空或已被删除(unset)，那么返回 word，并将 Variable 的值设置为 word。</td>
    </tr>
    <tr>
        <td align="left">${Variable:?message}</td>
        <td align="left">如果变量 Variable 为空或已被删除(unset)，那么将消息 message 送到标准错误输出，可以用来检测变量 Variable 是否可以被正常赋值。<br>
若此替换出现在Shell脚本中，那么脚本将停止运行。</td>
    </tr>
    <tr>
        <td align="left">${Variable:+word}</td>
        <td align="left">如果变量 Variable 被定义，那么返回 word，但不改变 Variable 的值。</td>
    </tr>
</table>




<h2 id="2-命令替换"><a href="#2-命令替换" class="headerlink" title="2.命令替换"></a><font size=3>2.命令替换</font></h2><h3 id="2-1使用格式"><a href="#2-1使用格式" class="headerlink" title="2.1使用格式"></a><font size=3>2.1使用格式</font></h3><p>命令替换是指 Shell 先执行命令，将输出结果暂时保存，在适当的地方输出。</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`command`  # 注意是反引号 ` `，按键位于 Esc下方</span><br></pre></td></tr></table></figure>

<h3 id="2-2使用实例"><a href="#2-2使用实例" class="headerlink" title="2.2使用实例"></a><font size=3>2.2使用实例</font></h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/bash</span></span><br><span class="line">DATE=`date` </span><br><span class="line">echo &quot;Date is $DATE&quot;</span><br></pre></td></tr></table></figure>

<p>运行结果为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Date is 2022年 02月 09日 星期三 18:27:51 CST</span><br></pre></td></tr></table></figure>

<h1 id="四、字典"><a href="#四、字典" class="headerlink" title="四、字典"></a><font size=3>四、字典</font></h1><p>在shell中是支持字典的，字典就是键值对，就类似这种样子的</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&quot;key&quot;=&quot;value&quot;</span><br></pre></td></tr></table></figure>

<p>字典，在其他语言中也称 map，使用 键-值对（key-value）存储，查找速度快。字典是无序的对象集合，元素是通过键来存取的，而不是通过索引值存取。字典是可变数据类型。</p>
<h2 id="1-字典的定义"><a href="#1-字典的定义" class="headerlink" title="1.字典的定义"></a><font size=3>1.字典的定义</font></h2><p>声明字典类型要用到关键词 declare ：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">declare -A dict_name</span><br></pre></td></tr></table></figure>

<p>这里一定要-A来声明，-a只能用来声明数组类型。需要注意的是在shell中变量可以不声明直接使用，但是字典不行，<strong>字典必须先声明，再使用</strong>。</p>
<h2 id="2-字典赋值"><a href="#2-字典赋值" class="headerlink" title="2. 字典赋值"></a><font size=3>2. 字典赋值</font></h2><p>我们有两种赋值方式：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">1.定义时直接赋值</span></span><br><span class="line">declare -A dict</span><br><span class="line">dict=([key1]=&quot;value1&quot; [key2]=&quot;value2&quot; [key3]=&quot;value3&quot;)</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">2.动态赋值</span></span><br><span class="line">declare -A dict</span><br><span class="line">dict[&#x27;key&#x27;]=value</span><br></pre></td></tr></table></figure>

<p>注意：</p>
<p>（1）如果键值对已经存在，会覆盖之前的值。</p>
<p>（2）key可以是数字或字符串。</p>
<h2 id="3-字典相关操作"><a href="#3-字典相关操作" class="headerlink" title="3. 字典相关操作"></a><font size=3>3. 字典相关操作</font></h2><h3 id="3-1-打印指定key的value"><a href="#3-1-打印指定key的value" class="headerlink" title="3.1 打印指定key的value"></a><font size=3>3.1 打印指定key的value</font></h3><ul>
<li>使用格式</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;dict_name[key]&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>使用实例</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line">declare -A dict</span><br><span class="line">dict=([0]=&quot;value1&quot; [1]=&quot;value2&quot; [&quot;a&quot;]=&quot;value3&quot;)</span><br><span class="line"></span><br><span class="line">echo $&#123;dict[0]&#125;</span><br><span class="line">echo $&#123;dict[1]&#125;</span><br><span class="line">echo $&#123;dict[&quot;a&quot;]&#125;</span><br></pre></td></tr></table></figure>

<p>打印结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp/STM32$ ./2.sh </span><br><span class="line">value1</span><br><span class="line">value2</span><br><span class="line">value3</span><br></pre></td></tr></table></figure>

<h3 id="3-2-打印所有key"><a href="#3-2-打印所有key" class="headerlink" title="3.2 打印所有key"></a><font size=3>3.2 打印所有key</font></h3><ul>
<li>使用格式</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;!dict_name[*]&#125;</span><br><span class="line">echo $&#123;!dict_name[@]&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>使用实例</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line">declare -A dict</span><br><span class="line">dict=([0]=&quot;value1&quot; [1]=&quot;value2&quot; [&quot;a&quot;]=&quot;value3&quot;)</span><br><span class="line">echo $&#123;!dict[*]&#125;</span><br></pre></td></tr></table></figure>

<p>打印结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp/STM32$ ./2.sh </span><br><span class="line">a 0 1</span><br></pre></td></tr></table></figure>

<h3 id="3-3-打印所有value"><a href="#3-3-打印所有value" class="headerlink" title="3.3 打印所有value"></a><font size=3>3.3 打印所有value</font></h3><ul>
<li>使用格式</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">echo $&#123;dict_name[*]&#125;</span><br><span class="line">echo $&#123;dict_name[@]&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>使用实例</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line">declare -A dict</span><br><span class="line">dict=([0]=&quot;value1&quot; [1]=&quot;value2&quot; [&quot;a&quot;]=&quot;value3&quot;)</span><br><span class="line">echo $&#123;dict[*]&#125;</span><br></pre></td></tr></table></figure>

<p>打印结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp/STM32$ ./2.sh </span><br><span class="line">value3 value1 value2</span><br></pre></td></tr></table></figure>

<h3 id="3-4-遍历"><a href="#3-4-遍历" class="headerlink" title="3.4 遍历"></a><font size=3>3.4 遍历</font></h3><ul>
<li>使用实例</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line">declare -A dict</span><br><span class="line">dict=([0]=&quot;value1&quot; [1]=&quot;value2&quot; [&quot;a&quot;]=&quot;value3&quot;)</span><br><span class="line">echo $&#123;dict[*]&#125;</span><br><span class="line"></span><br><span class="line">for key in $&#123;!dict[*]&#125;</span><br><span class="line">  do</span><br><span class="line">    echo &quot;$&#123;key&#125; : $&#123;dict[$&#123;key&#125;]&#125;&quot;</span><br><span class="line">  done</span><br></pre></td></tr></table></figure>

<p>打印结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp/STM32$ ./2.sh </span><br><span class="line">value3 value1 value2</span><br><span class="line">a : value3</span><br><span class="line">0 : value1</span><br><span class="line">1 : value2</span><br></pre></td></tr></table></figure>

<h3 id="3-5-不声明？"><a href="#3-5-不声明？" class="headerlink" title="3.5 不声明？"></a><font size=3>3.5 不声明？</font></h3><ul>
<li>使用实例</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="built_in">declare</span> -A dict</span></span><br><span class="line">dict=([0]=&quot;value1&quot; [1]=&quot;value2&quot; [&quot;a&quot;]=&quot;value3&quot;)</span><br><span class="line">echo $&#123;!dict[*]&#125;</span><br><span class="line"></span><br><span class="line">for key in $&#123;!dict[*]&#125;</span><br><span class="line">  do</span><br><span class="line">    echo &quot;$&#123;key&#125; : $&#123;dict[$&#123;key&#125;]&#125;&quot;</span><br><span class="line">  done</span><br></pre></td></tr></table></figure>

<p>打印结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp/STM32$ ./2.sh </span><br><span class="line">0 1</span><br><span class="line">0 : value3</span><br><span class="line">1 : value2</span><br></pre></td></tr></table></figure>

<p>发现我的 “a” 呢？怎么没了，原因就在于没了字典的声明，这样看上去就是一个数组了，数组是不支持字符串下标的，所以就没有a啦，这一点需要注意一下。</p>
<p>我们可以试一下数组支不支持字符下标：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_">#</span><span class="language-bash">!/bin/sh</span></span><br><span class="line"><span class="meta prompt_">#</span><span class="language-bash"><span class="built_in">declare</span> -A dict</span></span><br><span class="line">dict=([&quot;a&quot;]=&quot;value_a&quot; [&quot;b&quot;]=&quot;value_b&quot;)</span><br><span class="line">echo $&#123;dict[@]&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>打印结果如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">hk@vm:~/1sharedfiles/6temp/STM32$ ./2.sh </span><br><span class="line">value_b</span><br></pre></td></tr></table></figure>

<p>最终的结果就是数组里面只有下标 为 0 的值为 value_b。</p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/d8e0ae4.html">LV02-02-shell-02-变量与替换</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2022年02月21日 - 10:53</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/d8e0ae4.html" title="LV02-02-shell-02-变量与替换">https://sumumm.github.io/post/d8e0ae4.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV02-%E7%BC%96%E8%AF%91%E5%9F%BA%E7%A1%80/" rel="tag"><i class="fa fa-tag"></i> LV02-编译基础</a>
              <a href="/tags/shell%E8%84%9A%E6%9C%AC/" rel="tag"><i class="fa fa-tag"></i> shell脚本</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/fbb9bfa7.html" rel="prev" title="LV02-02-shell-03-运算符和语句">
                  <i class="fa fa-angle-left"></i> LV02-02-shell-03-运算符和语句
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/b8367f35.html" rel="next" title="LV02-02-shell-01-基础知识">
                  LV02-02-shell-01-基础知识 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">false</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
